﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.IO;
using System.IO.Compression;

namespace XP.Utilities.Utility
{
    public class Http
    {
        public static string Post(string url, string contents)
        {
            string result = string.Empty;

            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = "POST";
                request.ContentType = "text/xml; charset=utf-8";
                //request.Headers.Add("SOAPAction", SoapAction); //指定访问Web Service的命名空间及使用方法   
                //request.Headers.Add("ContentType", "text/xml; charset=utf-8"); //指定字符集  
                byte[] byteContents = System.Text.Encoding.UTF8.GetBytes(contents);
                request.ContentLength = byteContents.Length;

                // 提交要 Post 的内容。
                Stream requestStream = request.GetRequestStream();
                requestStream.Write(byteContents, 0, byteContents.Length);
                requestStream.Flush();
                requestStream.Close();

                // 获取 Post 后处理的返回值。
                HttpWebResponse res = (HttpWebResponse)request.GetResponse();
                Stream responseStream = res.GetResponseStream();
                StreamReader sr = new StreamReader(responseStream);
                result = sr.ReadToEnd();
                sr.Close();
                responseStream.Close();
            }
            catch
            {
            }

            return result;
        }
        public static string GetUrl()
        {
            string url = String.Format("http://{0}{1}/", System.Web.HttpContext.Current.Request.Url.Host + (System.Web.HttpContext.Current.Request.Url.Port == 80 ? "" : ":" + System.Web.HttpContext.Current.Request.Url.Port.ToString()), System.Web.HttpContext.Current.Request.ApplicationPath);
            return url;
        }
        public static string GetContent(string url)
        {
            string result = string.Empty;
            try
            {
                WebRequest webRequest = WebRequest.Create(url);
                WebResponse webResponse = webRequest.GetResponse();
                using (Stream stream = webResponse.GetResponseStream())
                {
                    using (StreamReader sReader = new StreamReader(stream))
                    {
                        result = sReader.ReadToEnd();
                    }
                }
                webRequest = null;
                webResponse = null;
            }
            catch { }
            return result;
        }
        #region 获取网页内容
        public static string GetWebContent(string url)
        {
            return Encoding.UTF8.GetString(getBytes(url, null));
        }
        public static string GetWebContent(string url, Encoding encoding)
        {
            return encoding.GetString(getBytes(url, null));
        }
        private static byte[] getBytes(string url, CookieContainer cookie)
        {
            int c = url.IndexOf("/", 10);
            byte[] data = null;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.CookieContainer = cookie;
            request.Referer = (c > 0 ? url.Substring(0, c) : url);
            request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)";
            request.Headers[HttpRequestHeader.AcceptEncoding] = "gzip, deflate";
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            string ce = response.Headers[HttpResponseHeader.ContentEncoding];
            int ContentLength = (int)response.ContentLength;
            Stream s = response.GetResponseStream();
            c = 1024 * 10;
            if (ContentLength < 0)
            {
                data = new byte[c];
                MemoryStream ms = new MemoryStream();
                int l = s.Read(data, 0, c);
                while (l > 0)
                {
                    Console.WriteLine("1--> " + l);
                    ms.Write(data, 0, l);
                    l = s.Read(data, 0, c);
                }
                data = ms.ToArray();
                ms.Close();
            }
            else
            {
                data = new byte[ContentLength];
                int pos = 0;
                while (ContentLength > 0)
                {
                    int l = s.Read(data, pos, ContentLength);
                    pos += l;
                    ContentLength -= l;
                    Console.WriteLine("2--> " + l);
                }
            }
            s.Close();
            response.Close();

            if (ce == "gzip")
            {
                Console.WriteLine("\n\n正在解压数据...");
                MemoryStream js = new MemoryStream();           // 解压后的流  
                MemoryStream ms = new MemoryStream(data);       // 用于解压的流  
                GZipStream g = new GZipStream(ms, CompressionMode.Decompress);
                byte[] buffer = new byte[c];                    // 读数据缓冲区     
                int l = g.Read(buffer, 0, c);                   // 一次读 10K     
                while (l > 0)
                {
                    Console.WriteLine("3--> " + l);
                    js.Write(buffer, 0, l);
                    l = g.Read(buffer, 0, c);
                }
                g.Close();
                ms.Close();
                data = js.ToArray();
                js.Close();
            }
            return data;
        }
        #endregion
        #region 下载图片
        public static string DownloadPicture(string url, string path)
        {
            string fileName = path + url.Substring(url.LastIndexOf("/") + 1);
            fileName = System.Web.HttpUtility.UrlDecode(fileName);
            if (File.Exists(fileName)) return fileName;
            System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
            System.Net.WebResponse response = request.GetResponse();
            using (System.IO.Stream stream = response.GetResponseStream())
            {
                if (!System.IO.Directory.Exists(path)) System.IO.Directory.CreateDirectory(path);
                using (System.IO.Stream outStream = System.IO.File.Create(fileName))
                {
                    byte[] buffer = new byte[1024];
                    int l;
                    do
                    {
                        l = stream.Read(buffer, 0, buffer.Length);
                        if (l > 0)
                            outStream.Write(buffer, 0, l);
                    }
                    while (l > 0);
                }
            }
            return fileName;
        }
        #endregion
        public static string GetIP()
        {
            if (System.Web.HttpContext.Current.Request.ServerVariables["HTTP_VIA"] != null)
            {
                return System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
            }

            else
            {
                return System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"].ToString();
            } 
        }
        public static string FilterHTML(string html)
        {
            System.Text.RegularExpressions.Regex regex1 = new System.Text.RegularExpressions.Regex(@"<script[\s\S]+</script *>", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            System.Text.RegularExpressions.Regex regex2 = new System.Text.RegularExpressions.Regex(@" href *= *[\s\S]*script *:", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            System.Text.RegularExpressions.Regex regex3 = new System.Text.RegularExpressions.Regex(@" no[\s\S]*=", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            System.Text.RegularExpressions.Regex regex4 = new System.Text.RegularExpressions.Regex(@"<iframe[\s\S]+</iframe *>", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            System.Text.RegularExpressions.Regex regex5 = new System.Text.RegularExpressions.Regex(@"<frameset[\s\S]+</frameset *>", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            System.Text.RegularExpressions.Regex regex6 = new System.Text.RegularExpressions.Regex(@"\<img[^\>]+\>", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            System.Text.RegularExpressions.Regex regex7 = new System.Text.RegularExpressions.Regex(@"</p>", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            System.Text.RegularExpressions.Regex regex8 = new System.Text.RegularExpressions.Regex(@"<p>", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            System.Text.RegularExpressions.Regex regex9 = new System.Text.RegularExpressions.Regex(@"<[^>]*>", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            html = regex1.Replace(html, ""); //过滤<script></script>标记 
            html = regex2.Replace(html, ""); //过滤href=javascript: (<A>) 属性 
            html = regex3.Replace(html, " _disibledevent="); //过滤其它控件的on...事件 
            html = regex4.Replace(html, ""); //过滤iframe 
            html = regex5.Replace(html, ""); //过滤frameset 
            html = regex6.Replace(html, ""); //过滤frameset 
            html = regex7.Replace(html, ""); //过滤frameset 
            html = regex8.Replace(html, ""); //过滤frameset 
            html = regex9.Replace(html, "");
            html = html.Replace(" ", "");
            html = html.Replace("</strong>", "");
            html = html.Replace("<strong>", "");
            return html;
        }
    }
}
